package com.kjlink.internal.workreport.third;

import cn.xuqiudong.common.base.craw.BaseCrawl;
import cn.xuqiudong.common.base.model.BaseResponse;
import cn.xuqiudong.common.util.JsonUtil;
import com.kjlink.internal.workreport.helper.PasswordHelper;
import com.kjlink.internal.workreport.user.model.User;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 登录到OA
 *
 * @author Vic.xu
 */
@Component
public class OaLoginUtil extends BaseCrawl {
    private static Logger logger = LoggerFactory.getLogger(OaLoginUtil.class);

    // http://oa.kjlink.com/KjlinkPmsBackend/tbRsUser/login?userCode=201088&password=654321
    private static String LOGIN_URL = "http://oa.kjlink.com/KjlinkPmsBackend/tbRsUser/login";

    @Value("${stl.login.url:}")
    public void setLoginUrl(String loginUrl) {
        if (StringUtils.isBlank(loginUrl)) {
            return;
        }
        LOGIN_URL = loginUrl;
    }

    public static BaseResponse<User> login(String userCode, String password) {
        OaLoginUtil util = new OaLoginUtil();
        try {
            // 2024-12-11  oa login修改为 前端小写md5 值
            password = PasswordHelper.encryptPassword(password).toLowerCase();
            String text = util.con(LOGIN_URL).data("userCode", userCode).data("password", password).getBodyText();
            logger.info("OA 登录返回结果：\n【{}】", text);
            OaResponse oaResponse = JsonUtil.jsonToObject(text, OaResponse.class);
            if (oaResponse.getCode() == 0 && oaResponse.getUser() != null) {
                OaUser OaUser = oaResponse.getUser();
                User user = new User(OaUser);
                return BaseResponse.success(user);
            }
            return BaseResponse.error("oa login result: " + oaResponse.getMsg());
        } catch (IOException e) {
            e.printStackTrace();
            return BaseResponse.error(e.getMessage());
        }
    }

    @Override
    protected int getTimeout() {
        return 30000;
    }

    public static void main(String[] args) {
        BaseResponse<User> login = login("201088", "654321");
        JsonUtil.printJson(login);
    }
}
